<template>
  <div class="scheduling-container">
    <!-- 操作按钮区 -->
    <div class="action-buttons">
      <el-button type="primary" @click="showAddCourseDialog = true">
        <i class="fas fa-plus" aria-hidden="true"/>
        新增排课
      </el-button>
      <el-button @click="refreshSchedule">
        <i class="fas fa-sync-alt" aria-hidden="true"/>
        刷新
      </el-button>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 今日时间轴概览 -->
      <div class="today-timeline">
        <TimeLineComponent :date="selectedDate" :segments="segments"/>
      </div>

      <!-- 排课详情区域 -->
      <div class="schedule-details">
        <!-- 左侧日历区域 -->
        <div class="calendar-section">
          <CalendarComponent
            :events="calendarEvents"
            :selected-date="selectedDate"
            @date-selected="handleDateSelected"
          />
        </div>

        <!-- 选中日期的排课列表 -->
        <div class="selected-date-schedule">
          <div class="section-header">
            <h3>{{ formatDate(selectedDate) }} 排课详情</h3>
            <span class="count-badge">{{ selectedDateCourses.length }} 节课</span>
          </div>

          <div v-if="selectedDateCourses.length !== 0" class="course-list">
            <CourseItem
              v-for="(course, index) in selectedDateCourses"
              :key="index"
              :course="course"
              @edit-course="handleEditCourse"
              @delete-course="handleDeleteCourse"
            />
          </div>

          <!-- 空状态 -->
          <div v-if="selectedDateCourses.length === 0" class="empty-state">
            <i class="fas fa-calendar-day" aria-hidden="true"/>
            <p>该日期暂无排课</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑课程对话框 -->
    <AddEditCourseDialog
      v-if="showAddCourseDialog"
      :visible="showAddCourseDialog"
      :course="editingCourse"
      @close="handleDialogClose"
    />
  </div>
</template>

<script>
import CalendarComponent from './CalendarComponent.vue'
import TimeLineComponent from './TimeLineComponent.vue'
import CourseItem from './CourseItem.vue'
import AddEditCourseDialog from './AddEditCourseDialog.vue'
import { deleteCourse, monthlyCourses } from '@/api/wordSystemCourse'

export default {
  name: 'SchedulingPage',
  components: {
    CalendarComponent,
    TimeLineComponent,
    CourseItem,
    AddEditCourseDialog
  },
  data() {
    return {
      // 当前选中日期
      selectedDate: new Date(),
      // 显示新增课程对话框
      showAddCourseDialog: false,
      // 正在编辑的课程
      editingCourse: null,
      // 所有课程数据
      courses: [],
      // 时间碎片轴
      segments: []
    }
  },
  computed: {
    // 日历事件数据（用于在日历上标记有课的日期）
    calendarEvents() {
      const events = {}
      this.courses.forEach(course => {
        const date = this.formatDateForCalendar(course.startTime)
        if (events[date]) {
          events[date]++
        } else {
          events[date] = 1
        }
      })
      return events
    },
    // 选中日期的课程
    selectedDateCourses() {
      const targetDate = new Date(this.selectedDate)
      targetDate.setHours(0, 0, 0, 0)

      return this.courses
        .filter(course => {
          const courseDate = new Date(course.startTime)
          courseDate.setHours(0, 0, 0, 0)
          return courseDate.getTime() === targetDate.getTime()
        })
        .sort((a, b) => a.startTime - b.startTime)
    }
  },
  watch: {
    'selectedDate'() {
      this.buildDailySchedule()
    }
  },
  mounted() {
    this.refreshSchedule()
  },
  methods: {
    // 处理日期选择
    handleDateSelected(date) {
      const oldMonth = this.selectedDate.getMonth()
      this.selectedDate = date
      if (oldMonth !== this.selectedDate.getMonth()) {
        this.refreshSchedule()
      }
    },
    // 格式化日期显示
    formatDate(date) {
      const d = new Date(date)
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
    },
    // 为日历格式化日期
    formatDateForCalendar(date) {
      const d = new Date(date)
      return `${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()}`
    },
    // 刷新排课数据
    async refreshSchedule() {
      const res = await monthlyCourses({
        year: this.selectedDate.getFullYear(),
        month: this.selectedDate.getMonth() + 1
      })
      this.courses = []
      res.forEach(item => {
        this.courses.push({
          id: item.id,
          title: item.student + ' ' + item.courseType,
          student: item.student,
          type: item.courseType,
          startTime: new Date(item.startTimeTimestamp * 1000),
          endTime: new Date(item.endTimeTimestamp * 1000),
          location: item.location,
          notes: item.notes,
          stuId: item.stuId,
          courseDurationTypeId: item.courseDurationType
        })
      })
      this.buildDailySchedule()
    },
    // 处理编辑课程
    handleEditCourse(course) {
      this.editingCourse = { ...course }
      this.showAddCourseDialog = true
    },
    // 处理删除课程
    handleDeleteCourse(id) {
      this.$confirm('确定要删除这节课吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteCourse({ id: id })
        await this.refreshSchedule()
        this.$notify.success('课程已删除')
      }).catch(() => {
        this.$notify.info('已取消删除')
      })
    },
    // 关闭对话框
    handleDialogClose() {
      this.showAddCourseDialog = false
      this.editingCourse = null
      this.refreshSchedule()
    },
    buildDailySchedule() {
      const dateStr = this.formatDate(this.selectedDate || new Date())
      const startOfDay = new Date(dateStr + 'T00:00:00')
      const endOfDay = new Date(dateStr + 'T23:59:59')

      // 1. 过滤并转换成 Date
      const dayData = this.courses
        .map(item => ({
          ...item,
          start: new Date(item.startTime),
          end: new Date(item.endTime)
        }))
        .filter(item => item.start >= startOfDay && item.start <= endOfDay)
        .sort((a, b) => a.start - b.start)

      const result = []
      let cursor = new Date(startOfDay)

      function formatTime(d) {
        return d.getHours() + ':' + d.getMinutes().toString().padStart(2, '0')
      }

      // 2. 构建时间片段
      for (const item of dayData) {
        if (item.start > cursor) {
          result.push({
            start: formatTime(cursor),
            duration: Math.floor((item.start - cursor) / 60000),
            type: 'valid',
            text: '可分配时间'
          })
        }

        result.push({
          start: formatTime(item.start),
          duration: Math.floor((item.end - item.start) / 60000),
          type: 'invalid',
          text: item.title
        })

        cursor = item.end
      }

      // 3. 补齐结尾
      if (cursor < endOfDay) {
        result.push({
          start: formatTime(cursor),
          duration: Math.floor((endOfDay - cursor + 1000) / 60000),
          type: 'valid',
          text: '可分配时间'
        })
      }

      this.segments = result
    }
  }
}
</script>

<style scoped>
.scheduling-container {
  padding: 20px;
  margin: 0 auto;
}

/* 操作按钮区 */
.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(8, 8, 8, 0.15);
  padding: 10px 5px;
  background-color: #ffffff;
}

.action-buttons .el-button {
  border-radius: 8px;
  padding: 8px 16px;
}

.action-buttons .el-button i {
  margin-right: 6px;
}

/* 主要内容区 */
.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
  box-sizing: border-box;
}

/* 日历区域 */
.calendar-section {
  width: 35%;
  box-sizing: border-box;
}

/* 排课详情区域 */
.schedule-details {
  flex: 1;
  display: flex;
  gap: 20px;
}

/* 今日时间轴 */
.today-timeline {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(8, 8, 8, 0.15);
  padding: 15px 20px;
  background-color: #fff;
}

.today-timeline h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

/* 选中日期的排课列表 */
.selected-date-schedule {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(8, 8, 8, 0.15);
  padding: 15px 20px;
  background-color: #fff;
  flex: 1; /* 原有的，保持水平方向伸缩 */
  /* 新增：让父容器垂直方向可伸缩，且内容溢出时不撑开容器 */
  display: flex;
  flex-direction: column; /* 子元素垂直排列 */
  max-height: calc(100vh - 290px); /* 限制父容器最大高度（关键）：屏幕高度 - 顶部区域高度 */
  min-height: 380px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.count-badge {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 12px;
  background-color: #f0f7ff;
  color: #0084ff;
  font-size: 12px;
  font-weight: 500;
}

/* 课程列表 */
.course-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  /* 核心新增属性 */
  flex: 1; /* 填充父容器的剩余垂直空间 */
  overflow-y: auto; /* 内容超出时垂直滚动 */
  box-sizing: border-box;
  padding: 0 5px; /* 可选：优化滚动体验 */
}

/* 自定义滚动条（仅现代浏览器支持） */
.course-list::-webkit-scrollbar {
  width: 6px; /* 滚动条宽度 */
}

.course-list::-webkit-scrollbar-track {
  background: #f5f5f5; /* 滚动条轨道颜色 */
  border-radius: 3px;
}

.course-list::-webkit-scrollbar-thumb {
  background: #ccc; /* 滚动条滑块颜色 */
  border-radius: 3px;
}

.course-list::-webkit-scrollbar-thumb:hover {
  background: #999; /* 滑块hover颜色 */
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-state i {
  font-size: 48px;
  color: #ddd;
  margin-bottom: 15px;
}

.empty-state p {
  margin: 0 0 20px 0;
  color: #999;
  font-size: 16px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .main-content {
    flex-direction: column;
  }

  .calendar-section {
    width: 100%;
  }
}
</style>
